<?php

namespace app\store\service;


use app\store\model\GroupOrder;
use think\facade\Db;
use WeChat\Pay;

class GroupOrderService
{
    public static function getGroupOrderList($param)
    {

        $store_id = session('store_id');


        $query = GroupOrder::alias('a')
                            ->field('a.id,a.order_no,a.discount_amount,a.real_amount,a.status,a.create_time,b.nickname,b.avatar,c.trade_method')
                            ->with('items')
                            ->join('user b','a.user_id=b.user_id')
                            ->join('order_trade c','a.id=c.order_id')
                            ->where('a.store_id',$store_id)
                            ->withAttr('trade_method',function ($value){
                                $type = [1 => '微信支付',2 => '支付宝支付',3 =>'余额支付', 4 => '积分兑换',5 => '免费拿'];
                                return $type[$value];
                            });

        if (!empty($param['start_time']) && !empty($param['end_time'])){
            $query->whereBetweenTime('a.create_time',$param['start_time'],$param['end_time']);
        }

        if (!empty($param['keyword'])){
            $query->whereOr('b.nickname',$param['keyword'])->where('a.order_no',$param['keyword']);
        }

        $orders = $query->order('a.id','desc')
            ->paginate(10);


        return $orders;
    }

    public static function findGroupOrder($order_id)
    {
        $order = Db::name('group_order')->alias('a')
            ->field('a.id,a.order_no,a.discount_amount,a.real_amount,a.receiver_phone,a.receiver_name,
                        a.province,a.city,a.county,a.address,a.status,a.create_time,c.nickname,c.avatar,d.trade_method,d.out_trade_no,
                        d.trade_time,d.trade_status,d.trade_fee')
            ->join('user c','a.user_id=c.user_id')
            ->join('group_order_trade d','a.id=d.group_order_id')
            ->where('a.id',$order_id)
            ->withAttr('trade_method',function ($value){
                $type = [1 => '微信支付',2 => '支付宝支付',3 =>'余额支付', 4 => '积分兑换',5 => '免费拿'];
                return $type[$value];
            })->withAttr('trade_status',function ($value){
                $type = [-1 => '交易失败',1 => '交易成功'];
                return $type[$value];
            })->withAttr('status',function ($value){
                $status = [-1 => '已取消',1 => '代付款', 2 => '待发货',3 => '待收货', 4=> '已完成'];
                return $status[$value];
            })->find();

        $order['items'] = Db::name('order_item')->where('order_id',$order['id'])->select();

        return $order;
    }


    public static function findPaymentConfig($group_order_id)
    {
        $trade = Db::name('group_order_trade')
            ->field('order_no,refund_no,trade_type,total_fee,store_id')
            ->where('group_order_id',$group_order_id)
            ->find();

        $paymentConfig = Db::name('payment_config')
            ->where(['store_id'=>$trade['store_id'],'type' => $trade['trade_type']])
            ->value('config');

        if (empty($paymentConfig)){
            return  [];
        }
        $config = json_decode($paymentConfig,true);

        $trade['config'] = $config;

        return  $trade;
    }


    public static function paymentQuery($group_order_id)
    {
        $trade = static::findPaymentConfig($group_order_id);
        switch ($trade['trade_type']){
            case 1 :
                $wechat = new Pay($trade['config']);
                $result = $wechat->queryOrder([
                    'out_trade_no' => $trade['order_no'],
                ]);
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
                    Db::name('group_order')->where('id',$group_order_id)->update([
                        'is_after_sale' => 1,
                        'after_sale_status' => 2,
                        'refund_reason' => '拼团失败,系统退款!'
                    ]);
                    return  json(['code'=>1,'msg' => '退款成功!']);
                }

                return json(['code' => 0, 'msg' => $result['err_code_des']]);
            case 2 :
                $pay = \We::AliPayApp($trade['config']);
                try {
                    $result = $pay->refund([
                        'out_trade_no' => $trade['order_no'],
                        'out_request_no' => $trade['refund_no'],
                        'refund_amount' => (float)$trade['total_fee'],
                    ]);
                    if ($result['code'] = 1000 && $result['msg'] == 'Success'){
                        return  json(['code'=>1,'msg' => '退款成功!']);
                    }

                    return  json(['code' => 1,'msg' => $result['sub_msg']]);
                }catch (\Exception $e){
                    return  ['code' => 0, 'msg' => $e->getMessage()];
                }

                return  $result;
        }
    }


    /**
     * 新增系统退款记录
     * */

    public static function saveSystemRefundRecord($data)
    {
        $result = Db::name('group_order_refund')->insert([
                    'group_order_id' => $data['group_order_id'],
                    'out_trade_no' => $data['out_trade_no'],
                    'refund_fee' => $data['trade_fee'],
                    'out_refund_no' => $data['out_refund_no'],
                    'refund_status' => 1,
                    'after_sale_status' => 1,
                    'refund_reason' => '拼团失败系统退款'
        ]);

        return $result;
    }


    /**
     * 修改售后状态
     * */

    public static function changeGroupOrderAfterStatus($group_order_id)
    {
        Db::name('group_order')->where('id',$group_order_id)->update(['status' => -1]);
        Db::name('group_order_refund')
            ->where('group_order_id',$group_order_id)
            ->update([
                'refund_time' => time(),
                'refund_status' => 2,
            ]);

    }

}